package com.itstyle.seckill.distributedlock.redis;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

@Slf4j
public class DistributedLockHandler {

    private RLock lock;

    private String lockKey;

    private volatile boolean locked = false;
    /**
     * 默认锁过期时间(毫秒)
     */
    private int leaseMsecs = 60 * 1000;

    /**
     * 获取锁等待时间(毫秒)
     */
    private int waitMsecs = 10 * 1000;

    public DistributedLockHandler(RedissonClient redissonClient, String lockKey) {
        this.lockKey = lockKey + "_lock";
        this.lock = redissonClient.getLock(this.lockKey);
    }

    public DistributedLockHandler(RedissonClient redissonClient, String lockKey, int waitMsecs) {
        this(redissonClient, lockKey);
        this.waitMsecs = waitMsecs;
    }

    public DistributedLockHandler(RedissonClient redissonClient, String lockKey, int waitMsecs, int leaseMsecs) {
        this(redissonClient, lockKey, waitMsecs);
        this.leaseMsecs = leaseMsecs;
    }

    public String getLockKey() {
        return lockKey;
    }

    public synchronized boolean lock() throws InterruptedException {
        locked = lock.tryLock(waitMsecs, leaseMsecs, TimeUnit.MILLISECONDS);
        return locked;
    }

    public synchronized void unlock() {
        if (locked) {
            lock.unlock();
            locked = false;
        }
    }
}
